﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Net;
using System.IO;
using System.Transactions;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int code = -1;

        string username = Request.Params["username"];

        if (username != null && username != "")
        {
            string password = Request.Params["password"];

            string[] s = username.Split('@');
            string id = s[0];
            string domain = s[1];

            code = AuthByBBS(domain, id, password);

            LoginCookie lc = new LoginCookie();
            lc.GUID = Guid.NewGuid();
            lc.ID = username;
            lc.Expires = DateTime.Now + TimeSpan.FromDays(90);

            if (code == 0)
            {
                try
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        var skidb = SkiWorldDataContext.GetInstance();

                        if (!skidb.Users.Any(u => u.ID == username))
                        {
                            User usr = new User();
                            usr.ID = username;
                            skidb.Users.InsertOnSubmit(usr);
                        }

                        skidb.LoginCookies.InsertOnSubmit(lc);

                        skidb.SubmitChanges();
                        ts.Complete();

                        code = 0;

                        HttpCookie ck = new HttpCookie("LOGIN", lc.GUID.ToString());
                        ck.Expires = DateTime.Now + TimeSpan.FromDays(90);
                        Response.SetCookie(ck);
                    }
                }
                catch (Exception)
                {
                    code = -2;
                }
            }
        }
        else
        {
            //Auth By Cookie
            try
            {
                HttpCookie ck = Request.Cookies["LOGIN"];
                if (ck != null)
                {
                    Guid guid = Guid.Parse(ck.Value);
                    LoginCookie lc = SkiWorldDataContext.GetInstance().LoginCookies.First(l => l.GUID == guid);
                    username = lc.ID;
                    code = 0;
                }
            }
            catch (Exception)
            {
                code = -2;
            }
        }

        if (0 == code)
        {
            Response.Write(string.Format("{{code:{0},username:'{1}'}}", code, username));
        }
        else
        {
            Response.Write("{code:" + code + "}");
        }
    }

    private int AuthByBBS(string domain, string id, string pwd)
    {
        try
        {
            string req = "http://m." + domain + "/user/login";

            //CookieContainer cookikes = new CookieContainer();
            HttpWebRequest hwp = (HttpWebRequest)HttpWebRequest.Create(req);
            hwp.AllowAutoRedirect = false;
            //hwp.CookieContainer = cookikes;
            hwp.Method = "POST";
            hwp.ContentType = "application/x-www-form-urlencoded";

            string postData = "id=" + id + "&passwd=" + HttpUtility.UrlEncode(pwd);
            StreamWriter requestWriter = new StreamWriter(hwp.GetRequestStream());
            requestWriter.Write(postData);
            requestWriter.Close();

            HttpWebResponse hwr = (HttpWebResponse)hwp.GetResponse();
            return hwr.StatusCode == HttpStatusCode.Redirect ? 0 : 1;
        }
        catch (Exception)
        {
            return -1;
        }
    }
}